package com.tutucms.service.admin.configuration;

import com.tutucms.repo.entity.User;
import com.tutucms.service.admin.common.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

/**
 * @title: swagger 配置
 * @author: wangxudong
 * @date: 2019/3/11 21:08
 * @version: 1.0
 * @modified :
 */
@Configuration
@EnableSwagger2
@Profile({"dev", "test"})
public class SwaggerConfig {

    @Value("${spring.profiles.active:dev}")
    private String profilesActive;

    @Autowired
    private UserContext userContext;

    @Bean
    public Docket createRestApi() {

        User mockUser = new User();
        mockUser.setId(100000L);
        ParameterBuilder aParameterBuilder = new ParameterBuilder();
        aParameterBuilder
                .parameterType("header")
                .name("Authorization")
                .defaultValue(userContext.login(mockUser))
                .description("header中Authorization 模拟admin用户登录")
                .modelRef(new ModelRef("string"))//指定参数值的类型
                .required(false).build(); //非必需，这里是全局配置
        List<Parameter> aParameters = new ArrayList<>();
        aParameters.add(aParameterBuilder.build());

        return new Docket(DocumentationType.SWAGGER_2)
                .enable(!profilesActive.equalsIgnoreCase("prod"))
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.tutucms.service.admin.controller"))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(aParameters);

    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("图图CMS api文档")
                .description("图图CMS swagger 文档")
                .termsOfServiceUrl("http://tutucms.com")
                //创建人
                .contact(new Contact("Trifolium Wang", "http://www.tutucms.com", "wangxudong@xuxinmedia.com"))
                .version("1.1")
                .build();
    }
}
